import { uri } from '@kit.ArkTS';

export default class UriParser {
  static parse(uriStr: string): UriOptions {
    return this.parseUri(new uri.URI(uriStr));
  }

  static parseUri(uri: uri.URI): UriOptions {
    return {
      scheme: uri.scheme,
      host: uri.host,
      path: uri.path,
      queryParameters: this.parseQuery(uri),
    }
  }

  private static parseQuery(uri: uri.URI): QueryParameters {
    const queryNames = uri.getQueryNames();
    return queryNames?.reduce(function (res, item) {
      res[item] = uri.getQueryValue(item);
      return res;
    }, {});
  }
}

export interface UriOptions {
  scheme: string;
  host: string;
  path?: string;
  queryParameters?: QueryParameters;
}

export interface QueryParameters {
  [key: string]:
    | undefined
    | string
    | string[]
    | boolean
    | boolean[]
    | number
    | number[]
    | QueryParameters
    | QueryParameters[];
}

